/*--------------------------------------------------------------------------*/
//Depends on dojo 1.1.0
/*--------------------------------------------------------------------------*/



/*--------------------------------------------------------------------------*/         
//Utility functions        
/*--------------------------------------------------------------------------*/ 
	function makeHiddenFormField(nameAndId, aForm, aValue){
		var value = aValue || ""
		var form = aForm || document.forms[0]
		var newHiddenField = document.createElement("input");
        newHiddenField.setAttribute("type", "hidden");
        newHiddenField.setAttribute("name", nameAndId);
        newHiddenField.setAttribute("id", nameAndId);
        newHiddenField.setAttribute("value", value);
        form.appendChild(newHiddenField)
         
	}    
	
/*
 This can save you some tedium. You need ids for
 our error displays to work.
 This funtion takes element names and applies them to ids, unless
 the id already exists.  If there's more than one element
 for a given name, adds the id to the first element.
 */
	function addIds(aForm){
		var form = aForm || document.forms[0]
		for(var i = 0; i < form.elements.length; i++){
		    var element = form.elements[i]
		    var name = element.name
	
	        var anElementThatAlreadyHasThisId = document.getElementById(name)
	        //The second check makes things work with IE.  Maybe typeof would work?
	        if(anElementThatAlreadyHasThisId != null && anElementThatAlreadyHasThisId.id!="")
	            continue
		var named = document.getElementsByName(name)
		if(named.length > 0)
	        	named[0].id = name
	
	    }
	}
	  
	  
	  
	function loadformFromJson(data, aForm){
	    var form =    aForm || document.forms[0]
	    var elmts_array = form.elements;
	    for(var i = 0, len=elmts_array.length; i < len; i++)
		{
		    var elem = elmts_array[i]
		if(elem.type == 'radio')  { //TODO Should also work for check boxes
		    console.log("We've got a radio button")
		    if(data[elem.name] == elem.value)
			elem.checked = true
		    continue
		}
		if(elem.name == null || elem.name == "")
			continue;
		if(eval("data." + elem.name)==undefined)
		    continue
		eval("elem.value = data." + elem.name)
	     }

	}
	
	
	function jsonInit(jsonStr, form){
   		makeHiddenFormField('jsonAttr', form)
    		addIds(form)
    		var data =  eval(jsonStr)
    		loadformFromJson(data.formJson, form)	
    		showErrorsInPlace(data)
    		return data
	}
	  
	//Dojo Dependency  
	function doJsonSubmit(aForm){
		var form =    aForm || document.forms[0]
        	var jsonAttr = document.getElementById("jsonAttr")	
        	jsonAttr.value = dojo.formToJson(form)
	    	form.submit
	}  
	
	//Note Will execute javascript attached to the data, but only if
	//the data node matches the name of one of the divs in the document.
	//We probably need another way to execute javascript without replacing
	//divs.
	function showPartials(data){
	    if( data.javascriptBefore !== undefined){
	    	eval(data.javascriptBefore)
	    }
	      var partialSuffix = 'Partial'
	      var divs = document.getElementsByTagName("div");	
	      for(var i = 0; i < divs.length; i++){
		    var element = divs[i]
		    if(element.id == undefined || element.id == "")
				continue;
		    if(! stringEndsWith(element.id, partialSuffix))
				continue
			//By this point we know we have an element id that ends with 'partial'.
			//Let's try to match it with a data attribute
			
			//First let's see if we there's a data.'element.id'
			var evalString = "var innerHTML = data." + element.id
		    eval(evalString)
		    //If not, then let's see if instead of data.xxxPartial, there's a data.xxx
		    //We'll count that as a match if it exists.
		    if(innerHTML == undefined){ 
		    	evalString = "var innerHTML = data." + removeSuffix(element.id, partialSuffix)
		        eval(evalString)
		    }
	        
	        var wasOriginallyUndefined = false
		    if(innerHTML == undefined){
		    	wasOriginallyUndefined = true
				innerHTML = ""
		    }
		    //If elemen.id starts with 'keep_', we won't erase it's previous value
		    // even if it wasn't sent up from the server this time.  In all other instances
	        //we apply the innerHtml.
		    if(! (keep(element.id) && wasOriginallyUndefined) ){
		    	element.innerHTML = innerHTML
		    	if(innerHTML !== "") //??Maybe I should gather up each of these innerHTMLs and 
		    		                 //apply javaScript only after all the rendering is done.
		    		findAndEvaluateJavascript(innerHTML)
		    }	
		    	
		}
	    if( data.javascriptAfter !== undefined){
	    	eval(data.javascriptAfter)
	    }
	}
	
	
	//dojo dependancy!!
	//This comes from Spring-Dojo.js.  Unfortunately it wasn't put into a separate method,
	//so I have to pull it out here. (But I might want to look at that chunk again if
	//I want to show a modal dialog!
	function findAndEvaluateJavascript(response){
		//Extract and store all <script> elements from the response
		var scriptPattern = '(?:<script(.|[\n|\r])*?>)((\n|\r|.)*?)(?:<\/script>)';
		var extractedScriptNodes = [];
		var matchAll = new RegExp(scriptPattern, 'img');
		var matchOne = new RegExp(scriptPattern, 'im');
	
		var scriptNodes = response.match(matchAll);
		if (scriptNodes != null)
		{
			for (var i=0; i<scriptNodes.length; i++)
			{
				var script = (scriptNodes[i].match(matchOne) || ['','',''])[2];
				script = script.replace(/<!--/mg,'').replace(/\/\/-->/mg,'').replace(/<!\[CDATA\[(\/\/>)*/mg,'').replace(/(<!)*\]\]>/mg,'');
				extractedScriptNodes.push(script);
			}
		}
		
		//Evaluate any script code
		dojo.forEach(extractedScriptNodes, function(script){
			dojo.eval(script);
		});	
	
	}	
		
	function showErrorsInPlace(data){		
	      var errorSuffix = 'Error'
	      var divs = document.getElementsByTagName("div");	
	      var totalErrors = 0
	      for(var i = 0; i < divs.length; i++){
		    var element = divs[i]
		    if(element.id == undefined || element.id == "")
			continue;
		    if(! stringEndsWith(element.id, errorSuffix))
		    	continue
		    var matchString = element.id.replace(errorSuffix, "")
		    var message = ""
		    if(! (data.errors == undefined || data.errors == "")){
		    	var evalString = "message = data.errors." + matchString
		    	eval(evalString)
		    	if(message == undefined)
		    		message = ""
		    	else
		    		totalErrors++
		    		
		    }
		    element.innerHTML = message
		  
		}
	        return (totalErrors > 0)
	}
	
	function stringEndsWith(str, ends){
		var index = str.indexOf(ends)
		if( ! (index > -1) ) return
		return index + ends.length == str.length
	}
	
	function removeSuffix(str, suffix){
		return str.split(suffix)[0]
	}
	
	function keep(str){
		var arr = str.split('_')
		if(arr.length == 0)
			return false
		return arr[0] == 'keep'
	
	}
/*--------------------------------------------------------------------------*/ 	